package com.caishi.lkx.user.excelListener;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.caishi.lkx.common.ienum.PlatformType;
import com.caishi.lkx.user.dto.MemberImportVo;
import com.caishi.lkx.user.ienum.type.Sex;
import com.caishi.lkx.user.ienum.type.UserAccountType;
import com.caishi.lkx.user.ienum.type.UserChannelType;
import com.caishi.lkx.user.ienum.type.UserType;
import com.caishi.lkx.user.model.DepartmentModel;
import com.caishi.lkx.user.model.GroupModel;
import com.caishi.lkx.user.model.LoginInfoModel;
import com.caishi.lkx.user.model.MemberModel;
import com.caishi.lkx.user.service.IDepartmentService;
import com.caishi.lkx.user.service.IGroupService;
import com.caishi.lkx.user.service.ILoginInfoService;
import com.zzw.common.Wrappers;
import com.zzw.common.exception.BizRuntimeException;

import com.caishi.lkx.user.login.LoginServiceComposite;

import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;

/**
 * @Author huangpeng
 * @Description
 * @Date 2022/3/22 10:24
 **/
@Slf4j
public class ImportMemberListener implements ReadListener<MemberImportVo> {
    final List<MemberImportVo> list = new ArrayList<>();
    final Map<String, String> failMap = new ConcurrentHashMap<>();
    private final UserType userType;
    private final GroupModel group;
    private final UserChannelType channelType;
    private final String createdBy;
    private final UserAccountType loginType;
    private final LoginServiceComposite loginServiceComposite;
    private final IGroupService groupService;
    private final IDepartmentService departmentService;
    private final ILoginInfoService loginInfoService;
    private final PlatformType platformType;

    public ImportMemberListener(LoginServiceComposite loginServiceComposite, IGroupService groupService, UserType userType, GroupModel group, UserChannelType channelType, PlatformType platformType, String createdBy, UserAccountType loginType, IDepartmentService departmentService, ILoginInfoService loginInfoService) {
        this.userType = userType;
        this.loginType = loginType;
        this.group = group;
        this.channelType = channelType;
        this.createdBy = createdBy;
        this.loginServiceComposite = loginServiceComposite;
        this.groupService = groupService;
        this.departmentService = departmentService;
        this.loginInfoService = loginInfoService;
        this.platformType = platformType;
    }


    @Override
    public void invoke(MemberImportVo memberImportVo, AnalysisContext analysisContext) {

        if (StringUtil.isBlank(memberImportVo.getUserName()) || StringUtil.isBlank(memberImportVo.getMobile())
                || StringUtil.isBlank(memberImportVo.getPassword()) || null == memberImportVo.getDepartmentId()) {
            throw new BizRuntimeException("导入失败,检查文件格式");
        }
        DepartmentModel one = departmentService.selectFirst(Wrappers.<DepartmentModel>lambdaQuery()
                .eq(DepartmentModel::getId, memberImportVo.getDepartmentId())
                .eq(DepartmentModel::getGroupId, group.getId()).select(DepartmentModel::getId));
        if (null == one) {
            throw new BizRuntimeException("不存在该组织编码");
        }

        String password = memberImportVo.getPassword();
        //大小写 数字六位
        String regex = "^(?=.*[0-9].*)(?=.*[A-Z].*)(?=.*[a-z].*).{6,}$";
        boolean matches = Pattern.matches(regex, password);
        if (!matches) {
            throw new BizRuntimeException("请输入6-20位密码,同时包含大小写字母及数字");
        }
        Long count = loginInfoService.selectCount(Wrappers.<LoginInfoModel>lambdaQuery().eq(LoginInfoModel::getAccount, memberImportVo.getUserName()));
        if (count != 0) {
            throw new BizRuntimeException("用户名已存在");
        }
        //
        memberImportVo.setDepartmentId(one.getId());
        list.add(memberImportVo);

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (CollUtil.isNotEmpty(list)) {
            list.parallelStream().forEach(vo -> {
                if (StrUtil.isNotBlank(vo.getMobile())) {
                    LoginInfoModel loginInfoModel = new LoginInfoModel();
                    loginInfoModel.setLoginType(loginType);
                    loginInfoModel.setAccount(vo.getUserName());
                    loginInfoModel.setCertificate(vo.getPassword());
                    MemberModel memberModel = new MemberModel();
                    memberModel.setMobile(vo.getMobile());
                    memberModel.setName(vo.getName());
                    memberModel.addUserType(userType);
                    memberModel.setCreatedBy(createdBy);
                    memberModel.setChannelType(channelType);
                    memberModel.setChannelPointer(createdBy);
                    memberModel.setModifyBy(createdBy);
                    memberModel.setGroupId(this.group.getId());
                    memberModel.setDepartmentId(vo.getDepartmentId());
//                    LocalDate userExpireTime = groupService.getUserExpireTime(group, platformType);
//                    LocalDateTime expire = null;
//                    if (null != userExpireTime) {
//                        expire = userExpireTime.atTime(23, 59, 59);
//                    }
//                    if (platformType.equals(PlatformType.KAOYAN)) {
//                        memberModel.setKaoyanExpireTime(expire);
//                    } else {
//                        memberModel.setExpireTime(expire);
//                    }
                    memberModel.setEmail(vo.getEmail());
                    if (StrUtil.isNotBlank(vo.getStuNo())) {
                        memberModel.setStuNo(vo.getStuNo());
                    }
                    if (StrUtil.isNotBlank(vo.getSex())) {
                        if ("男".equals(vo.getSex())) {
                            memberModel.setSex(Sex.boy);
                        } else if ("女".equals(vo.getSex())) {
                            memberModel.setSex(Sex.girl);
                        } else {
                            memberModel.setSex(Sex.unknown);
                        }
                    } else {
                        memberModel.setSex(Sex.unknown);
                    }
                    try {
                        loginServiceComposite.register(loginInfoModel, memberModel);
                    } catch (Exception e) {
                        log.error("用户导入失败:", e);
                        failMap.put(vo.getMobile(), e.getMessage());
                    }
                }
            });

        }
        if (!failMap.isEmpty()) {
            throw new BizRuntimeException("导入失败:" + failMap);
        }
    }


}
